﻿using System;
using System.Configuration;
using System.Net;
using System.Net.Sockets;
using System.Text;
using __Able.Network.Utils;
using Org.Mentalis.Network.ProxySocket;
using PDM.Packet.RequestPacket;

namespace PDM.Provider
{
    class PDMProvider
    {
        static void Main(string[] args)
        {
            IPAddress ip = IPAddress.Parse("0.0.0.0");
            int port = 12345;
            int.TryParse(ConfigurationManager.AppSettings["port"], out port);

            PDMProvider pdm = new PDMProvider();
            pdm.StartServer(new IPEndPoint(ip, port));

            Console.WriteLine("\r\nPress enter to exit...");
            Console.ReadLine();
        }

        public void StartServer(IPEndPoint ep)
        {
            ProxySocket s = new ProxySocket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            s.Bind(ep);
            s.Listen(10);
            Console.WriteLine("Listening on " + s.LocalEndPoint.ToString());
            Socket ss;

            byte[] packetLengthBuffer = new byte[2];
            int ret;
            ushort packetLength;

            while (true)
            {
                ss = (Socket)s.Accept();
                IPAddress ip = IPAddress.Parse(((IPEndPoint)ss.RemoteEndPoint).Address.ToString());
                Console.WriteLine("\nIncoming socket accepted. Receiving request from {0}...", ip.ToString());
                ret = 0;
                packetLength = 0;
                ret = ss.Receive(packetLengthBuffer, 0, 2, SocketFlags.None);
                if (ret > 0)
                {
                    packetLength = new ByteBuffer(packetLengthBuffer).GetUShort();
                    Console.WriteLine("PacketLength:\t{0}", packetLength);

                    byte[] _buf = new byte[packetLength];
                    ret = ss.Receive(_buf, 0, packetLength, SocketFlags.None);
                    if (ret > 0)
                    {
                        ByteBuffer buf = new ByteBuffer(_buf);
                        LoginRequestPacket loginPk = new LoginRequestPacket(buf);

                        Console.WriteLine("Version:\t{0}", BitConverter.ToString(loginPk.Version));
                        Console.WriteLine("Token:\t\t{0}", loginPk.Token);
                        Console.WriteLine("Username:\t{0}", loginPk.Username);
                        Console.WriteLine("Password:\t{0}", loginPk.Password);
                        Console.WriteLine("Tail:\t\t{0}", loginPk.Tail);
                    }
                }

                if (ret == 0)
                {
                    Console.WriteLine("Client closed connection too soon.");
                    ss.Close();
                    break;
                }

                // geting data from database
                string pdata = "{name:able,pwd:123456}";
                ret = 0;
                try
                {
                    Console.WriteLine("Sending data:");
                    while (ret != pdata.Length)
                    {
                        ret += ss.Send(Encoding.UTF8.GetBytes(pdata), ret, pdata.Length - ret, SocketFlags.None);
                    }
                    Console.WriteLine("{0}\n\n", pdata);
                    ss.Shutdown(SocketShutdown.Both);
                    ss.Close();
                }
                catch (Exception e)
                {
                    Console.WriteLine("Error while sending data to the client [" + e.Message + "].");
                    Console.WriteLine(e);
                }

                Console.WriteLine("Waiting for another connection...");
            }
        }
    }
}
